import {Component, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl} from '@angular/forms'

/**
 * forwardRef  引用自己因为现在 ImageListSelectComponent在源数据里面还没有被创建
 */

@Component({
  selector: 'app-image-list-select',
  templateUrl: './image-list-select.component.html',
  styleUrls: ['./image-list-select.component.scss'],
  providers:[{
      provide:NG_VALUE_ACCESSOR,
      useExisting:forwardRef(() => ImageListSelectComponent),
      multi:true
    }, {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => ImageListSelectComponent),
    multi: true
  }]
})
export class ImageListSelectComponent implements  ControlValueAccessor {



  @Input() cols:number = 6;
  @Input() rowHeight:string = '64px';
  @Input() title:string = '选择';
  @Input() items:string[] = [];
  @Input() userSvgIcon:boolean = false;
  @Input() itemWidth:string = '80px';

  selected:string

  private propagateChange = ( _:any ) => {};
  // 写入值
  writeValue(obj: any): void {
    this.selected = obj;
    // todo
  }
  // 表单发生变化发射出去
  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }
  // 聚焦过
  registerOnTouched(fn: any): void {}
  // 验证
  validate(c:FormControl):{[key:string]:any}{
    return this.selected ? null : {
      imageListInvalid:{
        valid:false
      }
    }
  }


  setDisabledState(isDisabled: boolean): void {
    throw new Error("Method not implemented.");
  }

  onChange(i){
    this.selected = this.items[i];
    // 发送回去
    this.propagateChange(this.selected)
  }

}
